package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.PmsPurchaseOrders;
import com.ruoyi.system.domain.WmsInventoryHistory;
import com.ruoyi.system.domain.WmsInventoryStatistics;
import com.ruoyi.system.enums.OperationType;
import com.ruoyi.system.enums.WmsInboundStatus;
import com.ruoyi.system.mapper.PmsPurchaseOrdersMapper;
import com.ruoyi.system.mapper.WmsInventoryHistoryMapper;
import com.ruoyi.system.mapper.WmsInventoryStatisticsMapper;
import com.ruoyi.system.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.WmsInboundMapper;
import com.ruoyi.system.domain.WmsInbound;
import com.ruoyi.system.service.IWmsInboundService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入库信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-17
 */
@Service
public class WmsInboundServiceImpl implements IWmsInboundService
{
    @Autowired
    private WmsInboundMapper wmsInboundMapper;
    @Autowired
    private WmsInventoryHistoryMapper wmsInventoryHistoryMapper;
    @Autowired
    private WmsInventoryStatisticsMapper wmsInventoryStatisticsMapper;
    @Autowired
    private GetOrderNoUtil getOrderNoUtil;
    @Autowired
    private PmsPurchaseOrdersMapper pmsPurchaseOrdersMapper;

    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 查询入库信息
     *
     * @param id 入库信息主键
     * @return 入库信息
     */
    @Override
    public WmsInbound selectWmsInboundById(Long id)
    {
        WmsInbound wmsInbound = wmsInboundMapper.selectWmsInboundById(id);

        WmsInventoryHistory wmsInventoryHistory = new WmsInventoryHistory();

        wmsInventoryHistory.setOperationId(id);

        List<WmsInventoryHistory> wmsInventoryHistories = wmsInventoryHistoryMapper.selectWmsInventoryHistoryDetailList(wmsInventoryHistory);

        wmsInbound.setInventoryHistoryList(wmsInventoryHistories);

        return wmsInbound;
    }

    /**
     * 查询入库信息列表
     *
     * @param wmsInbound 入库信息
     * @return 入库信息
     */
    @Override
    public TableDataInfo<WmsInbound> selectWmsInboundList(WmsInbound wmsInbound, PageQuery pageQuery)
    {
        Page<WmsInbound> page = wmsInboundMapper.selectWmsInboundList(pageQuery.build(), wmsInbound);
        return TableDataInfo.build(page);
    }

    /**
     * 新增入库信息
     *
     * @param wmsInbound 入库信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWmsInbound(WmsInbound wmsInbound) throws Exception {
        boolean flag = false;
        //新增入库信息
        if(WmsInboundStatus.STORED.getCode().equals(wmsInbound.getInboundStatus())){
            wmsInbound.setCreateTime(new Date());
            wmsInbound.setInboundUserId(LoginHelper.getUserId());
            flag = true;
        }
        int i = wmsInboundMapper.insertWmsInbound(wmsInbound);

        //插入二维码
        if(flag){
            WmsInbound wmsInboundOther = new WmsInbound();
            wmsInboundOther.setBarcodeImageUrl(getFileName(wmsInbound.getId()));
            wmsInboundOther.setId(wmsInbound.getId());
            wmsInboundMapper.updateWmsInbound(wmsInboundOther);
        }

        //新增入库商品明细信息
        for (WmsInventoryHistory wmsInventoryHistory : wmsInbound.getInventoryHistoryList()){
            wmsInventoryHistory.setOperationId(wmsInbound.getId());
            wmsInventoryHistory.setOperationNo(wmsInbound.getInboundOrderNo());
            wmsInventoryHistory.setOperationType(OperationType.INBOUND.getCode());
            wmsInventoryHistory.setCreateTime(new Date());
            wmsInventoryHistoryMapper.insertWmsInventoryHistory(wmsInventoryHistory);

            if(flag){
                //修改库存统计表的库存数量
                WmsInventoryStatistics wmsInventoryStatistics = new WmsInventoryStatistics();

                wmsInventoryStatistics.setProductId(wmsInventoryHistory.getProductId());
                wmsInventoryStatistics.setInventoryTotal(wmsInventoryHistory.getTotalQuantity());
                wmsInventoryStatisticsMapper.editInventoryStatistics(wmsInventoryStatistics);
            }
        }



        return i;
    }

    /**
     * 修改入库信息
     *
     * @param wmsInbound 入库信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateWmsInbound(WmsInbound wmsInbound) throws Exception {
        boolean flag = false;
        if(WmsInboundStatus.STORED.getCode().equals(wmsInbound.getInboundStatus())){
            wmsInbound.setCreateTime(new Date());
            wmsInbound.setInboundUserId(LoginHelper.getUserId());
            wmsInbound.setBarcodeImageUrl(getFileName(wmsInbound.getId()));
            flag = true;
        }else if(WmsInboundStatus.INVALID.getCode().equals(wmsInbound.getInboundStatus())){

            wmsInbound.setCreateTime(new Date());
            wmsInbound.setInboundUserId(LoginHelper.getUserId());
        }
        wmsInbound.setUpdateTime(DateUtils.getNowDate());
        //修改入库基本信息
        int i = wmsInboundMapper.updateWmsInbound(wmsInbound);

        /*pmsPurchaseOrdersMapper.update(new LambdaQueryChainWrapper<PmsPurchaseOrders>()
            .eq(PmsPurchaseOrders::getInboundId,wmsInbound.getId())
            .set(PmsPurchaseOrders::getStatus, "5")
        );*/

        pmsPurchaseOrdersMapper.update(
            null, // 实体对象（如果不需要设置实体，可以传 null）
            new LambdaUpdateWrapper<PmsPurchaseOrders>()
                .eq(PmsPurchaseOrders::getInboundId, wmsInbound.getId()) // WHERE inbound_id = ?
                .set(PmsPurchaseOrders::getStatus, "5") // SET status = '5'
        );

        List<WmsInventoryHistory> inventoryHistoryList = wmsInbound.getInventoryHistoryList();

        if(!WmsInboundStatus.INVALID.getCode().equals(wmsInbound.getInboundStatus())){
            Long[] ids = inventoryHistoryList.stream().map(WmsInventoryHistory::getId)  // 提取每个对象的id
                .toArray(Long[]::new);           // 转换为Long数组

            //删除商品明细
            wmsInventoryHistoryMapper.deleteWmsInventoryHistoryByIds(ids);

            for (WmsInventoryHistory wmsInventoryHistory : inventoryHistoryList) {
                wmsInventoryHistory.setOperationId(wmsInbound.getId());
                wmsInventoryHistory.setOperationNo(wmsInbound.getInboundOrderNo());
                wmsInventoryHistory.setOperationType(OperationType.INBOUND.getCode());
                wmsInventoryHistory.setCreateTime(new Date());
                //插入商品明细数据
                wmsInventoryHistoryMapper.insertWmsInventoryHistory(wmsInventoryHistory);

                if(flag){
                    //修改库存统计表的库存数量
                    WmsInventoryStatistics wmsInventoryStatistics = new WmsInventoryStatistics();

                    wmsInventoryStatistics.setProductId(wmsInventoryHistory.getProductId());
                    wmsInventoryStatistics.setInventoryTotal(wmsInventoryHistory.getTotalQuantity());
                    wmsInventoryStatisticsMapper.editInventoryStatistics(wmsInventoryStatistics);
                }
            }
        }

        return i;
    }

    /**
     * 批量删除入库信息
     *
     * @param ids 需要删除的入库信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteWmsInboundByIds(Long[] ids)
    {
        int i = wmsInboundMapper.deleteWmsInboundByIds(ids);
        wmsInventoryHistoryMapper.deleteWmsInventoryHistoryByOperationIds(ids);
        return i;
    }

    /**
     * 删除入库信息信息
     *
     * @param id 入库信息主键
     * @return 结果
     */
    @Override
    public int deleteWmsInboundById(Long id)
    {
        return wmsInboundMapper.deleteWmsInboundById(id);
    }

    /**
     * 获取入库单编号
     * @return
     */
    @Override
    public WmsInbound getInboundOrderNo() {
        WmsInbound wmsInbound = new WmsInbound();
        wmsInbound.setInboundOrderNo(getOrderNoUtil.getOrderNo("RK-"));
        return wmsInbound;
    }

    @Override
    public void clearOrderNo(){
        getOrderNoUtil.clearOrderNo();
    }

    public String getFileName(Long id) throws Exception {
        //生成二维码
        String filePath = profile+"/upload/barcode_img/";
        String fileName = BarcodeGeneratorUtil.generateBarcode(filePath, id.toString());

        return "/profile/upload/barcode_img/"+fileName;
    }
}
